//
//  NetWorksTools.m
//  GasCome
//
//  Created by zfc on 2019/11/1.
//  Copyright © 2019年 depelec. All rights reserved.
//

#import "NetWorksTools.h"
#import "NetWorkCallBack.h"

@implementation NetWorksTools


static NSTimeInterval   requestTimeout = 20.f;
static NSDictionary     *headers;


static NetWorksTools *_netWorksTools;
+(instancetype)allocWithZone:(struct _NSZone *)zone {

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (_netWorksTools == nil) {
            _netWorksTools = [super allocWithZone:zone];
        }
    });
    return _netWorksTools;
}

+(instancetype) shared {

    return [[self alloc] init];
}

-(id)copyWithZone:(NSZone *)zone {
    return _netWorksTools;
}

-(id)mutableCopyWithZone:(NSZone *)zone {
    return _netWorksTools;
}

- (void) requestWithNotTokenMethod:(NSInteger)method url:(NSString *)url params:(NSDictionary * __nullable)params successBlock:(void (^)(NSDictionary *response))successBlock failureBlock:(void (^)(NSError *error))failureBlock {
    [self noProblemRequestWithMethod:method url:url params:params successBlock:successBlock failureBlock:failureBlock];
}

- (void) requestWithMethod:(NSInteger)method url:(NSString *)url params:(NSDictionary * __nullable)params successBlock:(void (^)(NSDictionary *response))successBlock failureBlock:(void (^)(NSError *error))failureBlock {
    
    LoginModel *model = UserAccountManager.shared.user;

    //提前刷新Token
    NSInteger expirationTime = [model.expiration_time integerValue];

    NSInteger accessTokenTime = [[[model.access_token componentsSeparatedByString:@"_"] lastObject] integerValue] + expirationTime;

    NSInteger currentTime = [[NSDate date] timeIntervalSince1970];
    
        if (accessTokenTime < currentTime && accessTokenTime) {
            if (_hasRefresh) {
                return;
            }
            
            //去刷新
            [self refreshAccessToken:^(NSDictionary * _Nullable data) {
                //如果access token过期，返回错误，调用此block
                NSLog(@"刷新data:%@", data);
                if([[data objectForKey:@"code"] intValue] == 200){

                    NSDictionary *dataDic = data[@"data"];

                    LoginModel *model = UserAccountManager.shared.user;
                    model.access_token = dataDic[@"access_token"];
                    model.refresh_token = dataDic[@"refresh_token"];
                    model.expiration_time = dataDic[@"expiration_time"];
                    [[UserAccountManager shared] saveUser:model];

                    [self noProblemRequestWithMethod:method url:url params:params successBlock:successBlock failureBlock:failureBlock];
                }else{
                    dispatch_async(dispatch_get_main_queue(), ^{

                        NSLog(@"错误:显示重新登录页面1");
                        [CommonFunc showLogin:nil];
                        /*
                        if (UserAccountManager.shared.is_login) {
                            LoginModel *model1 = UserAccountManager.shared.user;
                            LoginModel *model = [[LoginModel alloc] init];
                            model1.access_token = @"";
                            model.refresh_token = model1.refresh_token;
                            [UserAccountManager.shared saveUser:model];
    //                        [CommonFunc showLogin:nil];
                        } else {
                            NSLog(@"错误:显示重新登录页面");
                            [CommonFunc showLogin:nil];
                        }
                        
                        [self noProblemRequestWithMethod:method url:url params:params successBlock:successBlock failureBlock:failureBlock];*/
                    });
                }
            }];
        } else {
            [self noProblemRequestWithMethod:method url:url params:params successBlock:successBlock failureBlock:failureBlock];
        }

}


- (void) noProblemRequestWithMethod:(NSInteger)method url:(NSString *)url params:(NSDictionary *)params successBlock:(void (^)(NSDictionary *response))successBlock failureBlock:(void (^)(NSError *error))failureBlock {

    NetWorkCallBack *manager = [self config];

    NSString *httpUrl = [NSString stringWithFormat:@"%@%@",localhttp, url];
//    NSString *httpUrl = url;


    switch (method) {
        case POST:{
            [manager POST:httpUrl parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {

            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                NSDictionary *dic = responseObject;
                if (successBlock) {
                    successBlock(dic);
                }
                NSLog(@"requestHeads-----%@", manager.requestSerializer.HTTPRequestHeaders);
                NSLog(@"method----%zd, requestUrl-----%@, params----%@", method, httpUrl, params);
                NSLog(@"requestResult-----%@", responseObject);

                
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
                if (failureBlock) {
                    failureBlock(error);
                }

                NSString *errResponse = [[NSString alloc] initWithData:(NSData *)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] encoding:NSUTF8StringEncoding];
                NSDictionary *json = [Untils dictionaryWithJsonString:errResponse];
                if ([json[@"code"] intValue] == 422) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                    [SVProgressHUD showInfoWithStatus:json[@"message"]];
                    });
                }
                NSLog(@"requestHeads-----%@", manager.requestSerializer.HTTPRequestHeaders);
                NSLog(@"method----%zd, requestUrl-----%@, params----%@", method, httpUrl, params);
                NSLog(@"error-----%@", error);


            }];
            break;
        }
        case GET:{

            [manager GET:httpUrl parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {

            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                NSDictionary *dic = responseObject;
                if (successBlock) {
                    successBlock(dic);
                }
                NSLog(@"requestHeads-----%@", manager.requestSerializer.HTTPRequestHeaders);
                NSLog(@"method----%zd, requestUrl-----%@, params----%@", method, httpUrl, params);
                NSLog(@"requestResult-----%@", responseObject);
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                if (failureBlock) {
                    failureBlock(error);
                }
                NSLog(@"requestHeads-----%@", manager.requestSerializer.HTTPRequestHeaders);
                NSLog(@"method----%zd, requestUrl-----%@, params----%@", method, httpUrl, params);
                NSLog(@"error-----%@", error);

                NSString *errResponse = [[NSString alloc] initWithData:(NSData *)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] encoding:NSUTF8StringEncoding];
                NSDictionary *json = [Untils dictionaryWithJsonString:errResponse];
                if ([json[@"code"] intValue] == 422) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                    [SVProgressHUD showInfoWithStatus:json[@"message"]];
                    });
                }
            }];
            break;
        }
        case DELETE:
        {
            [manager DELETE:httpUrl parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                NSDictionary *dic = responseObject;
                if (successBlock) {
                    successBlock(dic);
                }
                NSLog(@"requestHeads-----%@", manager.requestSerializer.HTTPRequestHeaders);
                NSLog(@"method----%zd, requestUrl-----%@, params----%@", method, httpUrl, params);
                NSLog(@"requestResult-----%@", responseObject);
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                if (failureBlock) {
                    failureBlock(error);
                }
                NSLog(@"requestHeads-----%@", manager.requestSerializer.HTTPRequestHeaders);
                NSLog(@"method----%zd, requestUrl-----%@, params----%@", method, httpUrl, params);
                NSLog(@"error-----%@", error);

                NSString *errResponse = [[NSString alloc] initWithData:(NSData *)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] encoding:NSUTF8StringEncoding];
                NSDictionary *json = [Untils dictionaryWithJsonString:errResponse];
                if ([json[@"code"] intValue] == 422) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                    [SVProgressHUD showInfoWithStatus:json[@"message"]];
                    });
                }
            }];
            break;
        }

        case PUT:
        {
            [manager PUT:httpUrl parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                NSDictionary *dic = responseObject;
                if (successBlock) {
                    successBlock(dic);
                }
                NSLog(@"requestHeads-----%@", manager.requestSerializer.HTTPRequestHeaders);
                NSLog(@"method----%zd, requestUrl-----%@, params----%@", method, httpUrl, params);
                NSLog(@"requestResult-----%@", responseObject);
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                if (failureBlock) {
                    failureBlock(error);
                }
                NSLog(@"requestHeads-----%@", manager.requestSerializer.HTTPRequestHeaders);
                NSLog(@"method----%zd, requestUrl-----%@, params----%@", method, httpUrl, params);
                NSLog(@"error-----%@", error);

                NSString *errResponse = [[NSString alloc] initWithData:(NSData *)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] encoding:NSUTF8StringEncoding];
                NSDictionary *json = [Untils dictionaryWithJsonString:errResponse];
                if ([json[@"code"] intValue] == 422) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                    [SVProgressHUD showInfoWithStatus:json[@"message"]];
                    });
                }
            }];
            break;
        }
    }

}



-(void)refreshAccessToken:(void(^)(NSDictionary * _Nullable data))refresh {

    _hasRefresh = YES;
    NSLog(@"查看——————————222");

    LoginModel *model = UserAccountManager.shared.user;
//    BOOL isSaleMan = [[NSUserDefaults standardUserDefaults] boolForKey:kIsSalesMan];

    NSURLSession *session = [NSURLSession sharedSession];

    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/merapi/v1/site/refresh",localhttp]];    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    NSString *localVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:headers];
    dic[@"device"] = @"iOS"; //设备类型
    dic[@"device-uuid"] = UIDevice.currentDevice.identifierForVendor.UUIDString; //设备唯一s码
    dic[@"device-version"] = UIDevice.currentDevice.systemVersion; //设备系统版本号
    dic[@"device-app-version"] = app_Version; //设备上当前app版本号
    dic[@"X-Api-Key"] = model.access_token; //Token
    dic[@"version-name"] = localVersion; //Token
    
    for (NSString *key in dic.allKeys) {
        if (dic[key] != nil) {
            [request addValue:dic[key] forHTTPHeaderField:key];
        }
    }
    
    
    request.HTTPBody = [[NSString stringWithFormat:@"refresh_token=%@&group=%@", model.refresh_token, @"ios"] dataUsingEncoding:NSUTF8StringEncoding];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0/*延迟执行时间*/ * NSEC_PER_SEC));
            WeakSelf;
            dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                weakSelf.hasRefresh = NO;
            });
        });
        
        NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        refresh(jsonDict);
    }];
    [dataTask resume];

}



- (NetWorkCallBack *) config {
//    [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;

    NetWorkCallBack *manager = [NetWorkCallBack manager];

    //默认解析模式
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];

    //配置请求序列化
    AFJSONResponseSerializer *serializer = [AFJSONResponseSerializer serializer];

    serializer.removesKeysWithNullValues = YES;

    //    [serializer setRemovesKeysWithNullValues:YES];

    manager.requestSerializer.stringEncoding = NSUTF8StringEncoding;

    manager.requestSerializer.timeoutInterval = requestTimeout;

    manager.responseSerializer = serializer;
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];

//    CFShow(CFBridgingRetain(infoDictionary));
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    LoginModel *model = UserAccountManager.shared.user;
    NSString *localVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];

    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:headers];
    dic[@"device"] = @"iOS"; //设备类型
    dic[@"device-uuid"] = UIDevice.currentDevice.identifierForVendor.UUIDString; //设备唯一s码
    dic[@"device-version"] = UIDevice.currentDevice.systemVersion; //设备系统版本号
    dic[@"device-app-version"] = app_Version; //设备上当前app版本号
    dic[@"X-Api-Key"] = model.access_token; //Token
    dic[@"version-name"] = localVersion; //Token



//    //提前刷新Token
//    NSInteger expirationTime = [model.expiration_time integerValue];
//
//    NSInteger accessTokenTime = [[[model.access_token componentsSeparatedByString:@"_"] lastObject] integerValue] + expirationTime;
//
//    NSInteger currentTime = [[NSDate date] timeIntervalSince1970];

//    if (accessTokenTime < currentTime && accessTokenTime) {
//        //去刷新
//        [self refreshAccessToken:^(NSDictionary * _Nullable data) {
//            //如果access token过期，返回错误，调用此block
//
//            if([[data objectForKey:@"code"] intValue] == 200){
//
//                NSDictionary *dataDic = data[@"data"];
//
//                LoginModel *model = UserAccountManager.shared.user;
//                model.access_token = dataDic[@"access_token"];
//                model.refresh_token = dataDic[@"refresh_token"];
//                model.expiration_time = dataDic[@"expiration_time"];
//                [[UserAccountManager shared] saveUser:model];
//
//            }else{
//                dispatch_async(dispatch_get_main_queue(), ^{
//
//                    if (UserAccountManager.shared.is_login) {
//                        LoginModel *model1 = UserAccountManager.shared.user;
//                        LoginModel *model = [[LoginModel alloc] init];
////                        model1.access_token = @"";
//                        model.refresh_token = model1.refresh_token;
//                        [UserAccountManager.shared saveUser:model];
////                        [CommonFunc showLogin:nil];
//                    } else {
//                        NSLog(@"错误:显示重新登录页面");
//                        [CommonFunc showLogin:nil];
//                    }
//                });
//            }
//        }];
//    }




//    NSLog(@"requestHeader-----%@", dic);

    for (NSString *key in dic.allKeys) {
        if (dic[key] != nil) {
            [manager.requestSerializer setValue:dic[key] forHTTPHeaderField:key];
        }
    }

    //配置响应序列化
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithArray:@[@"application/json",
                                                                              @"text/html",
                                                                              @"text/json",
                                                                              @"text/plain",
                                                                              @"text/javascript",
                                                                              @"text/xml",
                                                                              @"image/*",
                                                                              @"application/octet-stream",
                                                                              @"application/zip"]];

    return manager;
}

+ (void)configHttpHeader:(NSDictionary *)httpHeader {
    headers = httpHeader;
}

/*
#pragma mark - 检查网络
+ (void)checkNetworkStatus {
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];

    [manager startMonitoring];

    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {

        switch (status) {
            case AFNetworkReachabilityStatusNotReachable:
                networkStatus = YQNetworkStatusNotReachable;
                break;
            case AFNetworkReachabilityStatusUnknown:
                networkStatus = YQNetworkStatusUnknown;
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                networkStatus = YQNetworkStatusReachableViaWWAN;
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                networkStatus = YQNetworkStatusReachableViaWiFi;
                break;
            default:
                networkStatus = YQNetworkStatusUnknown;
                break;
        }

    }];
}*/

@end
